#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Time   :2021/1/26
# @Author :CJX
# @File   :program_opening_and_protection.py

import os
import re
import signal
import pymysql


# execute command, and return the information. 执行命令并返回命令输出信息
def execCmd(cmd):
    r = os.popen(cmd)
    text = r.read()
    r.close()
    return text


def doSomething():
    os.system('nohup python3 /home/pi/ph/i2c_sql.py >/dev/null  2>&1 &')


def stopi2c():
    processInfo = os.popen("ps -ef|grep i2c_sql.py|grep -v grep|awk '{print $2}'").readlines()
    for pid in processInfo:
        os.kill(int(pid), signal.SIGKILL)


# stop parent
def stopi2cParent():
    parentList = os.popen("ps -ef|grep i2c_sql.py|grep -v grep|awk '{print $2}'").readlines()
    for pid in parentList:
        os.kill(int(pid), signal.SIGKILL)


def stopAll():
    stopi2c()
    stopi2cParent()


if __name__ == '__main__':
    # ps -ef是linux查看进程信息指令，|是管道符号导向到grep去查找特定的进程,最后一个|是导向grep过滤掉grep进程：因为grep查看程序名也是进程，会混到查询信息里
    programIsRunningCmd = "ps -ef|grep i2c_sql.py|grep -v grep"
    programIsRunningCmdAns = execCmd(programIsRunningCmd)  # 调用函数执行指令，并返回指令查询出的信息
    ansLine = programIsRunningCmdAns.split('\n')  # 将查出的信息用换行符‘\b’分开
    # 判断如果返回行数>2则说明python脚本程序已经在运行，打印提示信息结束程序，否则运行脚本代码doSomething()
    if len(ansLine) == 2:
        con = pymysql.connect(
            host='localhost',
            port=3306,
            user='root',
            password='!qAz2WsX3edc',
            db='ph',
            charset='utf8'
        )
        cur = con.cursor()
        min = cur.execute("SELECT min(id) FROM i2c ")
        min = int(cur.fetchone()[0])
        max = cur.execute("SELECT max(id) FROM i2c ")
        max = int(cur.fetchone()[0]) - 1000

        sql2 = ("delete FROM i2c " + "WHERE id <= %s " % max + " and id >= %s" % min)
        cur.execute(sql2)
        con.commit()
        cur.close()
        print(len(ansLine))
        print("programName have been Running")
    else:
        stopAll()
        print("寄")
        doSomething()
